package com.example.demo.zjitc.server.filter;

import com.example.demo.zjitc.server.service.impl.SpManagerServiceImpl;
import com.example.demo.zjitc.server.service.impl.SpPermissionApiServiceImpl;
import com.example.demo.zjitc.server.service.impl.SpRoleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.io.SerializablePermission;
import java.util.Collection;
import java.util.List;

/**
 * Author: Wang
 * Date: 2022/1/2 18:36
 * 角色权限处理
 */
@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {

    @Autowired
    private SpRoleServiceImpl spRoleService;
    @Autowired
    private SpManagerServiceImpl managerService;
   @Autowired
    private SpPermissionApiServiceImpl spPermissionApiService;
    @Override
    public boolean hasPermission(Authentication authentication, Object targetUrl, Object permission) {


        //获得loadUserByUsername()方法的结果
         User user = (User) authentication.getPrincipal();
         System.out.println(user.toString());
        //获得loadUserByUsername()中注入的角色
        Collection<GrantedAuthority> authorities=user.getAuthorities();
        String rolename ="";
        for (GrantedAuthority authority:authorities)
        {
             rolename = authority.getAuthority();
        }
        System.out.println(rolename);
        String[] rolenamex = rolename.split("_");
        String[] rolenamex1 = rolenamex[1].split("}");
        System.out.println(rolenamex1[0]);
        //超级管理员放行
        if (rolenamex1[0].equals("superadmin"))
            return true;
        //角色查询权限
       List<String> rolejurs =  spRoleService.rolejurs(rolenamex1[0]);
       String url  = targetUrl.toString();
       String urltar = url.substring(1,url.length());
        //查询接口权限
       int jurnum = spPermissionApiService.jurmethof(urltar);
       System.out.println(jurnum);
       System.out.println(rolejurs.toString());
        for (int i=0;i<rolejurs.size();i++)
        {

            if (String.valueOf(jurnum).equals(rolejurs.get(i)))
            {
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
